package com.chuangs.custom.excel;

import com.alibaba.excel.EasyExcel;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;
import java.util.Locale;

/**
 * Work happily and live happily ~~
 *
 * @Description:
 * @Author: java开发-袁松
 * @Date: 2023/3/31
 **/
public class CustomToolsExcel {


    /**
     * @param sqlName 数据库表 或者文件名字
     * @param list    获取出来的数据集何
     * @param tClass  映射实体类
     * @Description:
     * @return: void
     * @Author: ys
     * @Date: 2023/3/24
     */
    public static void exports(String sqlName, List<?> list, Class<?> tClass, HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 设置防止中文名乱码 URLEncoder.encode(sqlName, "utf-8");
        // 文件下载方式(附件下载还是在当前浏览器打开)
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(sqlName, "utf-8") + ".xlsx");
        // 写入数据到excel
        EasyExcel.write(response.getOutputStream(), tClass).autoCloseStream(Boolean.FALSE).sheet("sheet1").doWrite(list);

    }

    /**
     * @param file  读取的文件
     * @param clazz 映射实体类
     * @Description:
     * @return: java.util.List<?>
     * @Author: ys
     * @Date: 2023/3/31
     */
    public static List<?> imports(File file, Class<?> clazz) throws FileNotFoundException {
        // 数据解析监听器
        CustomListenerExcel listenerExcel = new CustomListenerExcel();
        // 读取数据
        EasyExcel.read(new FileInputStream(file), clazz, listenerExcel).sheet().doRead();
        // 获取去读完成之后的数据
        return listenerExcel.getDataList();
    }

}
